const {
	reqGet,
	reqPost,
} = require('@utils/request')
const {
	$U_UserInfo,
	$U_SetItem,
	$U_GetItem,
} = require('@utils/storage')

async function loadProjectData(apiTestComp, projectId) {
	let projectData = null
	let {
		id,
		is_locked,
		locked_user,
		project_data,
	} = await reqGet('/ult/api', {
		project_id: projectId,
	});
	project_data = project_data.replace(/^["'`]|["'`]$/g, '')
	try {
		projectData = JSON.parse(project_data)
	} catch (e) {
		console.log('e', e)
	}
	apiTestComp.store = {
		projectData,
		currentAPI: null,
		currentRequestParameter: null,
		tmpResult: null,
		tmpResponseParameterMap: null,
	}
	let treeData = []
	let moduleArr = Object.values(projectData.modules)
	for (let i = 0; i < moduleArr.length; i++) {
		let module = moduleArr[i]
		module.children = Object.values(module.apis)
		treeData.push(module)
	}
	apiTestComp.store.currentAPI = treeData[0].children[0]
	apiTestComp.treeComp.tree('loadData', treeData)
	apiTestComp.testServerUrl.textbox('setValue', projectData.testServerUrl)
	loadAPIDetail(apiTestComp)
	return apiTestComp
}

/**
 * 加载接口详情信息
 * @param  {[type]} apiTestComp [description]
 * @param  {[type]} detail  [description]
 * @return {[type]}         [description]
 */
function loadAPIDetail(apiTestComp) {
	let {
		store,
		formComp,
		treeComp,
		requestParameterComp,
		responseParameterComp,
	} = apiTestComp;
	let node = store.currentAPI;
	let projectData = store.projectData;
	// 接口信息，从editProjectData中获取
	let moduleId = node && node.attributes && node.attributes.moduleId
	let detail = projectData.modules[moduleId].apis[node.id];
	if (!detail || !detail.attributes) {
		store.currentAPI = null
		return false
	}
	let {
		contentType,
		path,
		method,
		intro,
		requestParameterList,
		responseParameterList,
	} = detail.attributes
	formComp.form('load', {
		id: detail.id,
		contentType,
		path,
		method,
		intro,
	})
	try {
		requestParameterList = JSON.parse(requestParameterList)
		responseParameterList = JSON.parse(responseParameterList)
	} catch (e) {
		requestParameterList = []
		responseParameterList = []
	}
	if (store.currentRequestParameter && store.currentRequestParameter._treeId_) {
		requestParameterComp.treegrid('endEdit', store.currentRequestParameter._treeId_)
		store.currentRequestParameter = null
	}
	store.currentAPI = detail;
	requestParameterComp.treegrid('loadData', requestParameterList);
	node = treeComp.tree('find', detail.id)
	treeComp.tree('select', node.target)
}

module.exports = {

	loadProjectData,

	loadAPIDetail,
}